package com.micromsg.common.util;

import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

public class JasyptUtils {

    private static final String SECRET_KEY = "my-secret-key";
    private static final StandardPBEStringEncryptor ENCRYPTOR = new StandardPBEStringEncryptor();

    static {
        ENCRYPTOR.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
        ENCRYPTOR.setPassword(SECRET_KEY);
    }

    /**
     * 加密
     *
     * @param plaintext 明文
     * @return 密文
     */
    public static String encrypt(String plaintext) {
        return ENCRYPTOR.encrypt(plaintext);
    }

    /**
     * 解密
     *
     * @param ciphertext 密文
     * @return 明文
     */
    public static String decrypt(String ciphertext) {
        return ENCRYPTOR.decrypt(ciphertext);
    }

    /**
     * 验证密码
     *
     * @param plaintext  明文密码
     * @param ciphertext 密文密码
     * @return 验证成功返回true
     */
    public static boolean checkPassword(String plaintext, String ciphertext) {
        String decrypt = JasyptUtils.decrypt(ciphertext);
        return StringUtils.equals(plaintext, decrypt);
    }
}
